﻿using System;
using System.Collections.Generic;
using Autodesk.Revit.UI;

namespace RevitInteractiveUtility.ExternalEventManager
{
	public class ExternalEventManagerSingleton
	{
		private ExternalEventManagerSingleton()
		{
			this.m_ExEvent = ExternalEvent.Create(this.m_Handler);
			this.m_locker = new object();
		}

		public static ExternalEventManagerSingleton GetEventManger(bool ifReset = false)
		{
			if (ExternalEventManagerSingleton.m_singleTag == null)
			{
				ExternalEventManagerSingleton.m_singleTag = new ExternalEventManagerSingleton();
			}
			if (ifReset)
			{
				ExternalEventManagerSingleton.m_singleTag.ReSetRequest();
			}
			return ExternalEventManagerSingleton.m_singleTag;
		}

		public void AppendRequest(IRequest appendValue)
		{
			lock (this.m_locker)
			{
				this.m_Handler.AppendRequest(appendValue);
			}
		}

		public void SetRequestListModel(bool inputValue)
		{
			lock (this.m_locker)
			{
				this.m_Handler.IfOnly = inputValue;
			}
		}

		public void ReSetRequest()
		{
			lock (this.m_locker)
			{
				this.m_Handler.ReSetRequestList();
				ExternalEventData.LstInputValue = new Dictionary<int, object>();
			}
		}

		public bool DoRequest(int keyValue, UIApplication app, object parameters = null)
		{
			bool result;
			lock (this.m_locker)
			{
				if (!ExternalEventData.LstInputValue.ContainsKey(keyValue))
				{
					ExternalEventData.LstInputValue.Add(keyValue, null);
				}
				if (ExternalEventData.LstInputValue[keyValue] == null)
				{
					ExternalEventData.LstInputValue[keyValue] = parameters;
					this.m_Handler.RequestGeter.Make(keyValue);
					this.m_ExEvent.Raise();
					result = true;
				}
				else
				{
					result = false;
				}
			}
			return result;
		}

		private ExternalEventHandler m_Handler = new ExternalEventHandler();

		private ExternalEvent m_ExEvent;

		private object m_locker;

		private static ExternalEventManagerSingleton m_singleTag;
	}
}
